//
//  PhotoDetailViewController.swift
//  googlypuff
//
//  Created by Open on 2/4/15.
//  Copyright (c) 2015 open-groupe. All rights reserved.
//

import UIKit

private let RetinaToEyeScaleFactor: CGFloat = 0.5
private let FaceBoundsToSyeScaleFactory: CGFloat = 4.0


class PhotoDetailViewController: UIViewController {
    
    @IBOutlet var photoScrollView: UIScrollView!
    @IBOutlet var photoImageView: UIImageView!
    
     var image: UIImage!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        assert(image != nil, "Image not set; require to use view controller")
        photoImageView.image = image;
        
        if image.size.height <= photoImageView.bounds.size.height &&
            image.size.width <= photoImageView.bounds.size.width {
                photoImageView.contentMode = .Center
        }
        
        let overLayImage = faceOverlayImageForImage(image)
        fadeInNewImage(overLayImage)
        
    }
}

private extension PhotoDetailViewController {
    func faceOverlayImageForImage(image: UIImage) -> UIImage {
        let detector = CIDetector(ofType: CIDetectorTypeFace,
            context: nil,
            options: [CIDetectorAccuracyLow: CIDetectorAccuracyHigh])
        
        let newImage = CIImage(CGImage: image.CGImage)
        let features = detector.featuresInImage(newImage) as [CIFaceFeature]!
        
        
        
        UIGraphicsBeginImageContext(image.size)
        let imageRect = CGRect(x: 0,y: 0,width: image.size.width, height: image.size.height)
        
        image.drawInRect(imageRect, blendMode: kCGBlendModeNormal ,alpha: 1.0)
        
        let context = UIGraphicsGetCurrentContext()
        for faceFeature in features {
            let faceRect = faceFeature.bounds
            CGContextSaveGState(context)
        
        CGContextTranslateCTM(context, 0.0, imageRect.size.height)
        CGContextScaleCTM(context, 1.0, -1.0)
        
            if faceFeature.hasLeftEyePosition{
                let leftEyePosition = faceFeature.leftEyePosition
                let eyeWidth = faceRect.size.width / FaceBoundsToSyeScaleFactory
                let eyeHeight = faceRect.size.height / FaceBoundsToSyeScaleFactory
                let eyeRect = CGRect(x: leftEyePosition.x - eyeWidth /  2.0,
                    y: leftEyePosition.y - eyeHeight / 2.0,
                    width: eyeWidth ,
                    height: eyeHeight)
                drawEyeBallForFrame(eyeRect)
            }
            if faceFeature.hasRightEyePosition {
                let RightEyePosition = faceFeature.rightEyePosition
                let eyeWidth = faceRect.size.width / FaceBoundsToSyeScaleFactory
                let eyeHeight = faceRect.size.height / FaceBoundsToSyeScaleFactory
                let eyeRect = CGRect(x: RightEyePosition.x - eyeWidth / 2,
                    y: RightEyePosition.y - eyeHeight / 2,
                    width: eyeWidth,
                    height: eyeHeight)
                drawEyeBallForFrame(eyeRect)
            }
            CGContextRestoreGState(context)
        }
        let overLayImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return overLayImage
        
    }
    
    func faceRotationInRadians(leftEyepoint startPoint: CGPoint, rightEyepoint endPoint: CGPoint) -> CGFloat
    {
        let deltaX = endPoint.x - startPoint.x
        let deltaY = endPoint.y - startPoint.y
        let angleInRadians = CGFloat(atan2f(Float(deltaY), Float(deltaX)))
        
        return angleInRadians
    }
    
    func drawEyeBallForFrame(rect: CGRect)
    {
        let context = UIGraphicsGetCurrentContext()
        CGContextAddEllipseInRect(context, rect)
        CGContextSetFillColorWithColor(context, UIColor.whiteColor().CGColor)
        CGContextFillPath(context)
        
        var x: CGFloat
        var y: CGFloat
        var eyeSizeWidth: CGFloat
        var eyeSizeHeight: CGFloat
        eyeSizeWidth = rect.size.width * RetinaToEyeScaleFactor
        eyeSizeHeight = rect.size.height * RetinaToEyeScaleFactor
        
        x = CGFloat(arc4random_uniform(UInt32(rect.size.width - eyeSizeWidth)))
        y = CGFloat(arc4random_uniform(UInt32(rect.size.height - eyeSizeHeight)))
        
        x += rect.origin.x
        y += rect.origin.y
        
        let eyeSize = min(eyeSizeWidth,eyeSizeHeight)
        let eyeBallRect = CGRect(x: x, y: y, width: eyeSize, height: eyeSize)
        CGContextAddEllipseInRect(context, eyeBallRect)
        CGContextSetFillColorWithColor(context, UIColor.blackColor().CGColor)
        CGContextFillPath(context)
    }
    
    func fadeInNewImage(newImage: UIImage)
    {
        let tmpImageView = UIImageView(image: newImage)
        tmpImageView.autoresizingMask = .FlexibleWidth | .FlexibleHeight
        tmpImageView.contentMode = photoImageView.contentMode
        tmpImageView.frame = photoImageView.bounds
        tmpImageView.alpha = 0.0
        photoImageView.addSubview(tmpImageView)
        
        UIView.animateWithDuration(0.75, animations: {
            tmpImageView.alpha = 1.0
            }, completion: {
                finished in
                self.photoImageView.image = newImage
                tmpImageView.removeFromSuperview()
        })
        
    }
}

extension PhotoDetailViewController: UIScrollViewDelegate
{
      func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
        return photoImageView
    }
}



